// 创建Vue实例
new Vue({
    el: '#app',
    // 修改Vue的分隔符以避免与Jinja2冲突
    delimiters: ['[[', ']]'],
    data: {
        // 当前视图
        currentView: 'deviceList',
        // 当前菜单索引
        currentMenuIndex: '1-1',
        
        // 设备相关数据
        devices: [],
        availableDevices: [],
        selectedDevice: null,
        selectedDevices: [],
        deviceScreenUrl: '',
        commandResult: '',
        inputCommand: '',
        commandTab: '0',
        
        // 一机多控相关数据
        multiControlType: 'tap',
        tapX: 500,
        tapY: 500,
        swipeX1: 300,
        swipeY1: 600,
        swipeX2: 300,
        swipeY2: 300,
        inputText: '',
        
        // 任务相关数据
        tasks: [],
        taskForm: {
            name: '',
            description: '',
            script_id: '',
            priority: 3
        },
        taskRules: {
            name: [
                { required: true, message: '请输入任务名称', trigger: 'blur' }
            ],
            script_id: [
                { required: true, message: '请选择脚本', trigger: 'change' }
            ]
        },
        
        // 脚本相关数据
        scripts: [],
        scriptForm: {
            name: '',
            description: '',
            language: 'python',
            content: '',
            is_public: false
        },
        scriptRules: {
            name: [
                { required: true, message: '请输入脚本名称', trigger: 'blur' }
            ],
            content: [
                { required: true, message: '请输入脚本内容', trigger: 'blur' }
            ]
        },
        
        // 上传脚本相关数据
        uploadForm: {
            description: '',
            language: 'python',
            is_public: false
        },
        fileList: []
    },
    mounted() {
        // 初始化数据
        this.refreshDevices();
        this.refreshTasks();
        this.refreshScripts();
    },
    methods: {
        // 切换视图
        changeView(view, menuIndex) {
            this.currentView = view;
            // 更新当前菜单索引
            if (menuIndex) {
                this.currentMenuIndex = menuIndex;
                // 展开对应的子菜单
                const submenuIndex = menuIndex.split('-')[0];
                const openeds = this.$refs.menu.openeds;
                if (!openeds.includes(submenuIndex)) {
                    openeds.push(submenuIndex);
                }
            }
            
            // 切换视图时刷新对应数据
            if (view === 'deviceList') {
                this.refreshDevices();
            } else if (view === 'taskList') {
                this.refreshTasks();
            } else if (view === 'scriptList' || view === 'createTask') {
                this.refreshScripts();
            }
        },
        
        // 刷新设备列表
        refreshDevices() {
            axios.get('/api/devices')
                .then(response => {
                    this.devices = response.data.devices || [];
                    this.availableDevices = this.devices.filter(device => device.status === '在线');
                })
                .catch(error => {
                    this.$message.error('获取设备列表失败');
                    console.error('获取设备列表失败:', error);
                });
        },
        
        // 查看设备
        viewDevice(deviceId) {
            axios.get(`/api/devices/${deviceId}`)
                .then(response => {
                    this.selectedDevice = response.data.device;
                    this.currentView = 'deviceControl';
                    this.connectToDeviceScreen(deviceId);
                })
                .catch(error => {
                    this.$message.error('获取设备信息失败');
                    console.error('获取设备信息失败:', error);
                });
        },
        
        // 控制设备
        controlDevice(deviceId) {
            this.viewDevice(deviceId);
        },
        
        // 连接设备信息界面
        connectToDeviceScreen(deviceId) {
            // 不使用视频流，仅设置一个默认值以保持界面一致性
            this.deviceScreenUrl = '';
        },
        
        // 发送Home命令
        sendHomeCommand() {
            this.executeDeviceCommand('home');
        },
        
        // 发送Back命令
        sendBackCommand() {
            this.executeDeviceCommand('back');
        },
        
        // 发送Recent Apps命令
        sendRecentAppsCommand() {
            this.executeDeviceCommand('recent_apps');
        },
        
        // 执行自定义命令
        executeCommand() {
            if (!this.inputCommand) {
                this.$message.warning('请输入命令');
                return;
            }
            
            this.executeDeviceCommand('shell', this.inputCommand);
        },
        
        // 执行设备命令
        executeDeviceCommand(command, params = '') {
            axios.post(`/api/devices/${this.selectedDevice.device_id}/command`, {
                command: command,
                params: params
            })
            .then(response => {
                this.commandResult = response.data.result || '命令执行成功';
            })
            .catch(error => {
                this.$message.error('命令执行失败');
                console.error('命令执行失败:', error);
            });
        },
        
        // 停止设备控制
        stopDeviceControl() {
            this.selectedDevice = null;
            this.deviceScreenUrl = '';
            this.commandResult = '';
            this.changeView('deviceList');
        },
        
        // 全选设备
        selectAllDevices() {
            if (this.selectedDevices.length === this.availableDevices.length) {
                this.selectedDevices = [];
            } else {
                this.selectedDevices = this.availableDevices.map(device => device.device_id);
            }
        },
        
        // 执行一机多控
        executeMultiControl() {
            if (this.selectedDevices.length === 0) {
                this.$message.warning('请至少选择一台设备');
                return;
            }
            
            let controlData = {
                devices: this.selectedDevices,
                type: this.multiControlType
            };
            
            if (this.multiControlType === 'tap') {
                controlData.x = this.tapX;
                controlData.y = this.tapY;
            } else if (this.multiControlType === 'swipe') {
                controlData.x1 = this.swipeX1;
                controlData.y1 = this.swipeY1;
                controlData.x2 = this.swipeX2;
                controlData.y2 = this.swipeY2;
            } else if (this.multiControlType === 'text') {
                controlData.text = this.inputText;
                if (!controlData.text) {
                    this.$message.warning('请输入文本');
                    return;
                }
            }
            
            axios.post('/api/devices/multi-control', controlData)
                .then(response => {
                    this.$message.success('多控命令执行成功');
                })
                .catch(error => {
                    this.$message.error('多控命令执行失败');
                    console.error('多控命令执行失败:', error);
                });
        },
        
        // 刷新任务列表
        refreshTasks() {
            axios.get('/api/tasks')
                .then(response => {
                    this.tasks = response.data.tasks;
                })
                .catch(error => {
                    this.$message.error('获取任务列表失败');
                    console.error('获取任务列表失败:', error);
                });
        },
        
        // 查看任务
        viewTask(taskId) {
            // 这里应该打开任务详情弹窗
            this.$message.info('查看任务详情功能待实现');
        },
        
        // 取消任务
        cancelTask(taskId) {
            if (confirm('确定要取消该任务吗？')) {
                axios.post(`/api/tasks/${taskId}/cancel`)
                    .then(response => {
                        this.$message.success('任务已取消');
                        this.refreshTasks();
                    })
                    .catch(error => {
                        this.$message.error('取消任务失败');
                        console.error('取消任务失败:', error);
                    });
            }
        },
        
        // 提交任务表单
        submitTaskForm() {
            this.$refs.taskForm.validate((valid) => {
                if (valid) {
                    axios.post('/api/tasks', this.taskForm)
                        .then(response => {
                            this.$message.success('任务创建成功');
                            this.resetTaskForm();
                            this.changeView('taskList');
                        })
                        .catch(error => {
                            this.$message.error('任务创建失败');
                            console.error('任务创建失败:', error);
                        });
                } else {
                    return false;
                }
            });
        },
        
        // 重置任务表单
        resetTaskForm() {
            this.$refs.taskForm.resetFields();
        },
        
        // 获取任务状态标签类型
        getStatusType(status) {
            switch (status) {
                case '等待中':
                    return 'warning';
                case '运行中':
                    return 'primary';
                case '已完成':
                    return 'success';
                case '失败':
                    return 'danger';
                case '已取消':
                    return 'info';
                default:
                    return '';
            }
        },
        
        // 刷新脚本列表
        refreshScripts() {
            axios.get('/api/scripts')
                .then(response => {
                    this.scripts = response.data.scripts;
                })
                .catch(error => {
                    this.$message.error('获取脚本列表失败');
                    console.error('获取脚本列表失败:', error);
                });
        },
        
        // 查看脚本
        viewScript(scriptId) {
            // 这里应该打开脚本详情弹窗
            this.$message.info('查看脚本详情功能待实现');
        },
        
        // 删除脚本
        deleteScript(scriptId) {
            if (confirm('确定要删除该脚本吗？')) {
                axios.delete(`/api/scripts/${scriptId}`)
                    .then(response => {
                        this.$message.success('脚本已删除');
                        this.refreshScripts();
                    })
                    .catch(error => {
                        this.$message.error('删除脚本失败');
                        console.error('删除脚本失败:', error);
                    });
            }
        },
        
        // 提交脚本表单
        submitScriptForm() {
            this.$refs.scriptForm.validate((valid) => {
                if (valid) {
                    axios.post('/api/scripts', this.scriptForm)
                        .then(response => {
                            this.$message.success('脚本创建成功');
                            this.resetScriptForm();
                            this.changeView('scriptList');
                        })
                        .catch(error => {
                            this.$message.error('脚本创建失败');
                            console.error('脚本创建失败:', error);
                        });
                } else {
                    return false;
                }
            });
        },
        
        // 重置脚本表单
        resetScriptForm() {
            this.$refs.scriptForm.resetFields();
        },
        
        // 提交上传
        submitUpload() {
            const uploader = this.$refs.upload.uploadFiles[0];
            if (!uploader) {
                this.$message.warning('请选择要上传的文件');
                return;
            }
            
            // 构建FormData
            const formData = new FormData();
            formData.append('file', uploader.raw);
            formData.append('description', this.uploadForm.description);
            formData.append('language', this.uploadForm.language);
            formData.append('is_public', this.uploadForm.is_public);
            
            axios.post('/api/scripts/upload', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            .then(response => {
                this.$message.success('脚本上传成功');
                this.fileList = [];
                this.uploadForm = {
                    description: '',
                    language: 'python',
                    is_public: false
                };
                this.changeView('scriptList');
            })
            .catch(error => {
                this.$message.error('脚本上传失败');
                console.error('脚本上传失败:', error);
            });
        },
        
        // 处理上传成功
        handleUploadSuccess(response, file, fileList) {
            this.$message.success('文件上传成功');
        },
        
        // 处理上传失败
        handleUploadError(error, file, fileList) {
            this.$message.error('文件上传失败');
        }
    }
});